package cn.imokay.lock;


import java.util.concurrent.locks.ReentrantLock;

public class SaleTicket {
    public static void main(String[] args) {
        LTicket ticket = new LTicket();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }

        }, "aaa").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }

        }, "bbb").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }

        }, "ccc").start();
    }
}

class LTicket {
    private int number = 30;

    //创建可重入锁,lock可以响应等待线程的中断标识中断，synchronized不可以 但是可以自动释放锁
    /**
     * 公平与非公平锁，当追求性能，追求吞吐量时，是哟个非公平锁，因为在cpu核层面，减少了线程的切换，怎样效率高就会让哪个线程进行执行
     * 当追求多个任务雨露均沾时，用公平锁
     */
    private final ReentrantLock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + ":卖出" + (number--) + "剩余:" + number);
            }
        } finally {
            lock.unlock();
        }


    }
}
